/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewAuctionDlg.java
 *
 * Created on May 9, 2012, 1:05:07 AM
 */

import java.rmi.RemoteException;

import FlexTrade.WSAdaptor;
import common_classes.AuctionPrimitiveData;
import common_classes.Product;
import common_classes.ProviderData;

import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;

/**
 *
 * @author hieuht
 * User interface to place a new auction from provider to market
 */
public class NewAuctionDlg extends javax.swing.JDialog {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//a pre-defined list of products. Do not support adding product
    private String[] productList = {"TV LCD", "Laptop", "Camera", "Mobile Phone"};

    /** Creates new form NewAuctionDlg */
    public NewAuctionDlg(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
     }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        cboProduct = new javax.swing.JComboBox(productList);
        lblProduct = new javax.swing.JLabel();
        cboAuctionType = new javax.swing.JComboBox();
        lblAuctionType = new javax.swing.JLabel();
        txtAskingPrice = new javax.swing.JTextField();
        txtAskingPrice.setEditable(false);
        jLabel1 = new javax.swing.JLabel();
        txtTimeDuration = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        btnOK = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        txtAcceptablePrice = new javax.swing.JTextField();
        txtAcceptablePrice.setEditable(false);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        cboProduct.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboProductActionPerformed(evt);
            }
        });
        
        cboAuctionType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboAuctionTypeActionPerformed(evt);
            }
        });

        lblProduct.setText("Product");

        cboAuctionType.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Vickrey", "English", "Dutch" }));

        lblAuctionType.setText("Auction Type");

        txtAskingPrice.setText("Not applicable");
        txtAcceptablePrice.setText("Not applicable");

        jLabel1.setText("Asking Price");

        txtTimeDuration.setText("0");

        jLabel2.setText("Time Duration");

        btnOK.setText("OK");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });
        

        txtAcceptablePrice.setColumns(10);
        
        JLabel lblAcceptablePrice = new JLabel("Acceptable Price");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(layout.createSequentialGroup()
        					.addGap(49)
        					.addGroup(layout.createParallelGroup(Alignment.LEADING)
        						.addComponent(lblProduct)
        						.addComponent(lblAuctionType)
        						.addComponent(jLabel1)
        						.addComponent(jLabel2)
        						.addComponent(lblAcceptablePrice))
        					.addGap(33)
        					.addGroup(layout.createParallelGroup(Alignment.LEADING)
        						.addComponent(txtTimeDuration)
        						.addComponent(cboAuctionType, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        						.addComponent(cboProduct, GroupLayout.PREFERRED_SIZE, 166, GroupLayout.PREFERRED_SIZE)
        						.addComponent(txtAskingPrice, GroupLayout.PREFERRED_SIZE, 129, GroupLayout.PREFERRED_SIZE)
        						.addComponent(txtAcceptablePrice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
        				.addGroup(layout.createSequentialGroup()
        					.addGap(118)
        					.addComponent(btnOK, GroupLayout.PREFERRED_SIZE, 83, GroupLayout.PREFERRED_SIZE)
        					.addGap(94)
        					.addComponent(btnCancel, GroupLayout.PREFERRED_SIZE, 79, GroupLayout.PREFERRED_SIZE)))
        			.addContainerGap(112, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addGap(34)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(cboAuctionType, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(lblAuctionType))
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(lblProduct)
        				.addComponent(cboProduct, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        			.addGap(18)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(txtAskingPrice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jLabel1))
        			.addGap(18)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(txtAcceptablePrice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(lblAcceptablePrice))
        			.addGap(25)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabel2)
        				.addComponent(txtTimeDuration, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        			.addPreferredGap(ComponentPlacement.RELATED, 41, Short.MAX_VALUE)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(btnOK)
        				.addComponent(btnCancel))
        			.addGap(23))
        );
        getContentPane().setLayout(layout);

        pack();
    }// </editor-fold>

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        //close the input box
        this.dispose();
    }                                         

    private void cboProductActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    }        
    
    private void cboAuctionTypeActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
    	//index of combo box starts from 0 ==> have to plus 1 to get auction type 
    	//which starting from 1
    	int selectedAuctionType = cboAuctionType.getSelectedIndex() + 1;
    	switch(selectedAuctionType){
    	case 1: 	//Vickrey auction
    		this.txtAcceptablePrice.setText("Not applicable");
    		this.txtAcceptablePrice.setEditable(false);
    		this.txtAskingPrice.setText("Not applicable");
    		this.txtAskingPrice.setEditable(false);
    		break;
    	case 2: 	//English Auction
    		this.txtAcceptablePrice.setText("Not applicable");
    		this.txtAcceptablePrice.setEditable(false);
    		this.txtAskingPrice.setText("Not applicable");
    		this.txtAskingPrice.setEditable(false);
    		break;
    	case 3:		//Dutch Auction
    		this.txtAcceptablePrice.setText("0");
    		this.txtAcceptablePrice.setEditable(true);
    		this.txtAskingPrice.setText("0");
    		this.txtAskingPrice.setEditable(true);
    		break;
    	default:	//invalid auction type
    		System.out.println("Invalid auction type");
    		return;
    	}
    } 

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        //create product object. Product ID equals to the index of that item in combo box
        Product product = new Product(cboProduct.getSelectedIndex(), (String)cboProduct.getSelectedItem());
        //create primitive data for the auction
        auctionPrimitiveData = new AuctionPrimitiveData();
        auctionPrimitiveData.setProduct(product);
        auctionPrimitiveData.setProvider(this.providerData);
    	auctionPrimitiveData.setTimeDuration(Long.parseLong(txtTimeDuration.getText()));
        if(cboAuctionType.getSelectedIndex() == (IAuction.DUTCH_AUCTION_TYPE - 1)) { //if auction type is Dutch
           	auctionPrimitiveData.setAskingPrice(Float.parseFloat(txtAskingPrice.getText()));
        	auctionPrimitiveData.setReservcePrice(Float.parseFloat(txtAcceptablePrice.getText()));
        	auctionPrimitiveData.setAcceptablePrice(0);
        }
        auctionPrimitiveData.setAuctionType(cboAuctionType.getSelectedIndex() + 1);
        //provider.requestNewAuction(auctionPrimitiveData);
        if (service != null) {
    		try {

				if (!service.receiveNewAuctionRequestFromProvider(auctionPrimitiveData)) {
					System.out.println("Cannot add auction to market");
					return;
				}
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				System.out.println("Exception");
				e.printStackTrace();
			}
        }


        //add this new auction to table in main user interface
        /*
        String strAuctiontype = "Invalid";
        switch(auctionPrimitiveData.auctionType){
        case 1: 	//Vickrey
        	strAuctiontype = "Vickrey";
        	break;
        case 2:	//English
        	strAuctiontype = "English";
        	break;
        case 3:	//Dutch
        	strAuctiontype = "Dutch";
        	break;
        default:
        	System.out.println("Invalid auction type.");
        }
        String[] addedRow = {auctionPrimitiveData.uniqueAuctionID,
        					 auctionPrimitiveData.product.getProductName(),
        					 strAuctiontype,
        					 Float.toString(auctionPrimitiveData.acceptablePrice),
        					 IAuction.AUCTION_IN_PROGRESS
        					 };
        this.provider.model.addRow(addedRow);
        */
        this.dispose();
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewAuctionDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewAuctionDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewAuctionDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewAuctionDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                NewAuctionDlg dialog = new NewAuctionDlg(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    public void setProvider(Provider _provider){
    	//this.provider = _provider;
    }
    
    public Provider getProvider(){
    	return null;
    	//return this.provider;
    }
    
    public AuctionPrimitiveData getAuctionPrimitiveData(){
    	return this.auctionPrimitiveData;
    }
    
    public void setProviderData(ProviderData _providerData){
    	this.providerData = _providerData;
    }
    
    
    public ProviderData getProviderData(){
    	return this.providerData;
    }
    
    public void setService(WSAdaptor _adapter) {
    	this.service = _adapter;
    }
    // Variables declaration - do not modify
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnOK;
    private javax.swing.JComboBox cboAuctionType;
    private javax.swing.JComboBox cboProduct;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lblAuctionType;
    private javax.swing.JLabel lblProduct;
    private javax.swing.JTextField txtAskingPrice;
    private javax.swing.JTextField txtTimeDuration;
    private javax.swing.JTextField txtAcceptablePrice;
    // End of variables declaration
	private WSAdaptor service;
    //public Provider provider;
    public ProviderData providerData;
    public AuctionPrimitiveData auctionPrimitiveData;
}
